package cn.edu.ujn.multiple.controller;

import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.ui.Model;
import cn.edu.ujn.multiple.model.BaseDict;
import cn.edu.ujn.multiple.model.User;
import cn.edu.ujn.multiple.service.IBaseDictService;
import cn.edu.ujn.multiple.service.IUserService;

@Controller
public class UserController {

	@Autowired
	private IUserService userService;
	@Autowired
	private IBaseDictService baseDictService;



	// 访问登录页面
	@GetMapping("/login.action")
	public String toLogin() {
		return "login";
	}

	// 登录操作
	@PostMapping("/login.action")
	public String login(String usercode, String password, String verifyCode, Model m, HttpSession session) {
		User user = userService.findUser(usercode, password);
		String code = (String) session.getAttribute("piccode");
		System.out.println(user.toString());
		if (verifyCode.toUpperCase().equals(code) && user != null) {
			session.setAttribute("USER_SESSION", user);
			return "redirect:customer";
		} else if (!verifyCode.toUpperCase().equals(code)) {
			m.addAttribute("msg", "验证码输入错误！");
		} else {
			m.addAttribute("msg", "账号或密码错误，请重新输入!");
		}
		return "login";
	}

	// 退出登录
	@RequestMapping("/logout.action")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:login.action";
	}

	// 忘记密码
	@GetMapping("/forget")
	public String toForget() {
		return "forget";
	}

	@PostMapping("/forget")
	public String forget(User user) {
		User newUser = userService.findByCode(user);
		newUser.setUserPassword(user.getUserPassword());
		userService.update(newUser);
		return "redirect:login.action";
	}

	// 用户注册
	@GetMapping("/enroll")
	public String toEnroll() {
		return "enroll";
	}

	@PostMapping("/enroll")
	public String enroll(User user) {
		User insert = userService.insert(user);
		if (insert.getUserId() > 0) {
			return "redirect:login.action";
		} else {
			return "redirect:enroll";
		}
	}
	
	@GetMapping("/setting")
	public String toSetting() {
		return "setting";
	}

}